package com.zju.DoctorGo.controller;

import com.zju.DoctorGo.entity.Appointment;
import com.zju.DoctorGo.entity.Result;
import com.zju.DoctorGo.entity.Review;
import com.zju.DoctorGo.mapper.ReviewMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/api/review") // 定义了这个控制器的基础路由
public class ReviewController {
    @Autowired
    private ReviewMapper reviewMapper;

    // 通过id获取评价信息
    @GetMapping("/getById")
    public Review getReviewById(@RequestParam("id") Long id) {
        return reviewMapper.selectById(id);
    }

    // 获取某个病人的所有预约信息
    @CrossOrigin
    @GetMapping("/getByPatientId")
    public java.util.List<Review> getReviewsByPatientId(@RequestParam("id") int id) {
        return reviewMapper.selectList(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Review>().eq("patient_id", id));
    }

    // 获取某个医生的所有预约信息
    @GetMapping("/getByDoctorId")
    public java.util.List<Review> getReviewsByDoctorId(@RequestParam("id") int id) {
        return reviewMapper.selectList(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Review>().eq("doctor_id", id));
    }

    // 创建评价信息
    @PostMapping("/create")
    public Result createReview(@RequestBody Review review) throws Exception{
        try{
            reviewMapper.insert(review);
            return Result.success(review);}
        catch (Exception e){
            return Result.error(e.getMessage());
        }
    }

    // 更新评价信息
    @PutMapping("/update")
    public Review updateReview(@RequestParam("id") int id, @RequestBody Review review) {
        review.setReviewId(id);
        reviewMapper.updateById(review);
        return review;
    }

    // 删除评价信息
    @DeleteMapping("/delete")
    public Result deleteReview(@RequestParam("id") Long id) {
        int res = reviewMapper.deleteById(id);
        if(res == 1) return Result.success();
        return Result.error("删除失败");
    }

    // 获取所有评价信息
    @GetMapping("/getAll")
    public java.util.List<Review> getAllReviews() {
        return reviewMapper.selectList(null);
    }


    // 获取某个医生的平均评分
    @GetMapping("/getAverageRating")
    public Double getAverageRatingByDoctorId(@RequestParam("id") Long id) {
        java.util.List<Review> reviews = reviewMapper.selectList(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Review>().eq("doctor_id", id));
        if (reviews.size() == 0) {
            return 0.0;
        }
        int sum = 0;
        for (Review review : reviews) {
            sum += review.getRating();
        }
        return (double) sum / reviews.size();
    }

}
